var groupId;
var page;
var pageElement;
var fileId;
var groupName;
var elementId;
var jsoneditor_data;
var jsoneditor_NewData;
var elementListData;
$(function () {
    // 页面初始化时默认调用第一页数据
    query(1);

    jsoneditor_data = new JSONEditor(document.getElementById("data_source"), getCNOptions({mode: 'code'}), {});
    jsoneditor_NewData = new JSONEditor(document.getElementById("new_dataSource"), getCNOptions({mode: 'code'}), {});

    //编辑元素组按钮
    $("#multiplyImg").on('click', '.ownStyle button.edit', function () {
        var url = $(this).closest(".ownStyle").find("a.tpl-table-images-content-i>img").attr("src");
        groupId = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("group-id");
        fileId = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("group-file-id");
        groupName = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("group-name");
        var orderNumber = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("order-number");
        $('#groupName').val(groupName);
        $('#EditOrderNumber').val(orderNumber);
        $('#imageId').attr('src', url);
        $("#doc-modal-1").modal({
            relatedTarget: this,
            closeViaDimmer: false, // 点击外部空白处不关闭弹窗
            closeOnConfirm: false, // 返回信息提示也不关闭弹窗
            keyboard: false, //按下esc键不会被关闭
        });
    });

    //编辑 元素 按钮
    $("#multiplyElement").on('click', '.ownStyle button.edit', function () {
        var url = $(this).closest(".ownStyle").find("a.tpl-table-images-content-i>img").attr("src");
        elementId = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("element-id");
        fileId = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("element-file-id");
        var elementName = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("element-name");
        $('#edit_element_name').val(elementName);
        $('#image_edit_element').attr('src', url);
        //循环获取所有的element configJson
        for (var i = 0; i < elementListData.length; i++) {
            var element_id =  elementListData[i].elementId;
            if(element_id == elementId){
                jsoneditor_data.setText(JSON.parse(JSON.stringify(elementListData[i].configJson)));
            }
        }
        $("#editElementData").modal({
                relatedTarget: this,
                closeViaDimmer: false, // 点击外部空白处不关闭弹窗
                closeOnConfirm: false, // 返回信息提示也不关闭弹窗
                keyboard: false, //按下esc键不会被关闭
            }
        );
    });


    //查看元素按钮
    $("#multiplyImg").on('click', '.ownStyle button.am-btn-warning', function () {
        groupId = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("group-id");
        queryElement();
        groupName = $(this).closest(".ownStyle").find(".tpl-table-images-content-i-time").attr("group-name");
        $('#groupQueryName').val(groupName);

        $('#queryElement').modal({
            relatedTarget: this,
            closeViaDimmer: false, // 点击外部空白处不关闭弹窗
            closeOnConfirm: false, // 返回信息提示也不关闭弹窗
            keyboard: false, //按下esc键不会被关闭
        });
    });

    //新增按钮
    $('#insertNewElement').on('click', function () {
        $('#insertElement').modal({
            relatedTarget: this,
            closeViaDimmer: false, // 点击外部空白处不关闭弹窗
            closeOnConfirm: false, // 返回信息提示也不关闭弹窗
            keyboard: false, //按下esc键不会被关闭
        });
    });

    //新增元素按钮
    $('#insertNewElementData').on('click', function () {
        $('#insertElementData').modal({
            relatedTarget: this,
            closeViaDimmer: false, // 点击外部空白处不关闭弹窗
            closeOnConfirm: false, // 返回信息提示也不关闭弹窗
            keyboard: false, //按下esc键不会被关闭
        });
    });

    //查询 元素组 按钮
    $('#queryElementForName').on('click', function () {
        var groupName = $('#searchForName').val();
        queryByName(groupName);
    })

    //查询 元素 按钮
    $('#queryElementButton').on('click', function () {
        var elementName = $('#searchForElementName').val();
        queryByElementName(elementName);
    })

});

/**
 * 获取数据
 * @param page 页码（当前所在第几页）
 */
function query(pageCurrent) {
    $.ajax({
        type: "post",
        url: ctp + "/element/list",
        cache: false,
        data: JSON.stringify({"current": !pageCurrent ? 1 : pageCurrent, "size": 15}),
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            if (result.code == "200") {
                // 每次切换到下一页时清空当前div中的数据
                $("#multiplyImg").empty();
                // 循环添加图片表格
                listImageData(result.data.records);
                // 调用分页工具显示分页 id, pageNo, pageSize, pageTotal
                initPage('page', result.data.current, result.data.size, result.data.total);
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}

// 循环拼接图标表格窗格
function listImageData(list) {
    // 渲染页面多个图片div
    // 首先拿到页面需要渲染的div
    // 循环往div里面添加值和渲染html
    var i = 0;

    $.each(list, function () {
        var groupId = list[i].groupId;
        var groupName = list[i].groupName;
        var url = ctp + "/static/" + list[i].fileUrl;
        var fileId = list[i].fileId;
        var createTime = list[i].createTime;
        var status = list[i].status;
        var orderNumber = list[i].orderNumber;
        $("#multiplyImg").append(
            '<div class="tpl-table-images-content  ownStyle">' +
            '<div class="tpl-table-images-content-i-time" order-number = "'+orderNumber+'" group-id ="'+groupId+'" group-file-id = "'+fileId+'" group-name = "'+groupName+'">' +
            '元素组名称:' + groupName + '</div>' +
            '<a href="javascript:;" class="tpl-table-images-content-i">' +
            '<img src=\"' + url + '\" alt="" onerror="showDefaultImg(this)" class="list-show-img">' +
            ' </a>' +
            '<div class="tpl-table-images-content-block">' +
            '<div class="tpl-i-font">发布时间:' + new Date(createTime).format("yyyy-MM-dd hh:mm:ss") + '</div>' +
            '<div class="am-btn-toolbar">' +
            '<div class="am-btn-group am-btn-group-xs tpl-edit-content-btn">' +
            '<button type="button" class="edit am-btn am-btn-default am-btn-secondary">' +
            '<span class="am-icon-edit"></span> 编辑' +
            '</button>' +
            '<button type="button" class="am-btn am-btn-default am-btn-warning">' +
            '<span class="am-icon-archive"></span> 元素' +
            '</button>' +
            '<button type="button" class="am-btn am-btn-default am-btn-danger" onclick = "deleteMultiplyImg(' + groupId + ')">' +
            '<span class="am-icon-trash-o"></span> 删除' +
            '</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>');
        i++;
    });
}

function showDefaultImg(img) {
    img.src = "static/img/noPicture.png";
    //不循环执行
    img.onerror = null;
}


/**
 * 页面分页工具栏
 * @param id html id
 * @param pageNo 当前页
 * @param pageSize 一页多少条
 * @param pageTotal 总条数
 */
function initPage(id, pageNo, pageSize, pageTotal) {
    page = fm_page({
        id: id,
        pageNo: (pageNo - 1) <= 0 ? 0 : (pageNo - 1),
        pageSize: pageSize,
        pageCount: pageTotal,
        pageChange: function (pageNo) {
            query(pageNo + 1);
        }
    });
}

//删除 大屏元素组
function deleteMultiplyImg(data) {
    var moduleIds = [];
    moduleIds.push(data);
    var msg = "您真的确定要删除吗？\n\n请确认！";
    if (confirm(msg) == true) {
        $.ajax({
            type: "post",
            url: ctp + "/element/delete",
            cache: false,
            data: JSON.stringify(moduleIds),
            dataType: "json",
            contentType: "application/json",
            success: function (result) {
                if (result.code == "200") {
                    alert("删除成功");
                    query(1);
                } else {
                    alert(result.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    } else {
        return false;
    }
}

//上传方法
function uploadData(operation) {
    debugger;
    var formData = new FormData();
    formData.append('fileId', fileId);
    if (operation == 'insert') {//新增
        formData.append('operation', 'insert');
        formData.append('groupName', $('#groupNewName').val());
        formData.append('orderNumber', $('#orderNumber').val());
    } else {//编辑
        formData.append('groupId', groupId);
        formData.append('groupName', $('#groupName').val());
        formData.append('orderNumber', $('#EditOrderNumber').val());
    }
    $.ajax({
        type: "post",
        url: ctp + "/element/uploadData",
        cache: false,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (result) {
            if (result.code == "200") {
                query(1);
                alert(result.data);
                $('#insertElement').modal('close');
                $("#doc-modal-1").modal('close');

                $('#imageId').attr('src', '');
                $('#imageNewId').attr('src', 'static/img/noPicture.png');

                //清空输入框的内容
                $('#groupNewName').val('');
                $('#form_imageNewFile').val('');
                $('#orderNumber').val('')

                $('#groupName').val('');
                $('#form_imageFile').val('');
                $('#EditOrderNumber').val('')
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}

//查询通过 元素组名称
function queryByName(name) {
    var parm = {"groupName": name, "current": 1, "size": 15};
    $.ajax({
        type: "post",
        url: ctp + "/element/list",
        cache: false,
        data: JSON.stringify(parm),
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            if (result.code == "200") {
                // 每次切换到下一页时清空当前div中的数据
                $("#multiplyImg").empty();
                // 循环添加图片表格
                listImageData(result.data.records);
                // 调用分页工具显示分页
                initPage('page', result.data.current, result.data.size, result.data.total);
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}

//上传图片
function uploadImage(operation) {
    var imageData;
    var formData = new FormData();
    if (operation == 'insert') { //新增
        imageData = $('#form_imageNewFile').val();
        if (imageData.length != 0) {
            formData.append("file", $('#form_imageNewFile')[0].files[0]);
            formData.append("operation", operation);
        }
    } else {//修改
        imageData = $('#form_imageFile').val();
        if (imageData.length != 0) {
            formData.append("fileId", fileId);
            formData.append("file", $('#form_imageFile')[0].files[0]);
        }

    }

    if (imageData.length != 0) {
        $.ajax({
            type: "post",
            url: ctp + "/sysFile/uploadImage",
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (result) {
                if (result.code == "200") {
                    var url = ctp + "/static/" + result.data.fileUrl;
                    fileId = result.data.fileId;
                    //上传成功之后清空输入框的值
                    if (operation == 'insert') {
                        $('#imageNewId').attr('src', url);
                    } else {
                        $('#imageId').attr('src', url);
                    }
                } else {
                    alert(result.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    }
}


//查看元素详细按钮
function queryElement(pageCurrent) {
    $.ajax({
        type: "post",
        url: ctp + "/element/query",
        cache: false,
        data: JSON.stringify({"current": !pageCurrent ? 1 : pageCurrent, "size": 5, "groupId": groupId}),
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            if (result.code == "200") {
                elementListData = result.data.records;
                // 每次切换到下一页时清空当前div中的数据
                $("#multiplyElement").empty();
                // 循环添加图片表格
                listElementData(result.data.records);
                // 调用分页工具显示分页 id, pageNo, pageSize, pageTotal
                initPageElement('pageElement', result.data.current, result.data.size, result.data.total);
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}

//表格数据渲染
function listElementData(list) {
    // 渲染页面多个图片div
    // 首先拿到页面需要渲染的div
    // 循环往div里面添加值和渲染html
    var i = 0;
    $.each(list, function () {
        var elementId = list[i].elementId;
        var groupId = list[i].groupId;
        var elementName = list[i].elementName;
        var url = ctp + "/static/" + list[i].fileUrl;
        var fileId = list[i].fileId;
        var configJson = list[i].configJson;
        $("#multiplyElement").append(
            '<div class="tpl-table-images-content  ownStyle">' +
            '<div class="tpl-table-images-content-i-time" element-id = "'+elementId+'" element-name = "'+elementName+'" element-file-id = "'+fileId+'">' +
            '元素名称:' + elementName + '</div>' +
            '<a href="javascript:;" class="tpl-table-images-content-i">' +
            '<img src=\"' + url + '\" alt="" onerror="showDefaultImg(this)" class="list-show-img">' +
            ' </a>' +
            '<div class="tpl-table-images-content-block">' +
            '<div class="am-btn-toolbar">' +
            '<textarea rows="3" cols="20" style="display:none;">'+configJson+'</textarea>'+
            '<div class="am-btn-group am-btn-group-xs tpl-edit-content-btn">' +
            '<button type="button" class="edit am-btn am-btn-default am-btn-secondary">' +
            '<span class="am-icon-edit"></span> 编辑' +
            '</button>' +
            '<button type="button" class="am-btn am-btn-default am-btn-danger" onclick = "deleteElementImg(' + elementId + ')">' +
            '<span class="am-icon-trash-o"></span> 删除' +
            '</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>'
        );
        i++;
    });
}


/**
 * 元素页面分页工具栏
 * @param id html id
 * @param pageNo 当前页
 * @param pageSize 一页多少条
 * @param pageTotal 总条数
 */
function initPageElement(id, pageNo, pageSize, pageTotal) {
    pageElement = fm_page({
        id: id,
        pageNo: (pageNo - 1) <= 0 ? 0 : (pageNo - 1),
        pageSize: pageSize,
        pageCount: pageTotal,
        pageChange: function (pageNo) {
            queryElement(pageNo + 1);
        }
    });
}

//删除元素
function deleteElementImg(elementId) {
    var formData = new FormData();
    formData.append("elementId", elementId);
    var msg = "您真的确定要删除吗？\n\n请确认！";
    if (confirm(msg) == true) {
        $.ajax({
            type: "post",
            url: ctp + "/element/deleteElement",
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (result) {
                if (result.code == "200") {
                    alert("删除成功");
                    queryElement(1);
                } else {
                    alert(result.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    } else {
        return false;
    }
}

//上传元素图片
function uploadElementImage(operation) {
    var imageData;
    var formData = new FormData();
    if (operation == 'insert') { //新增
        imageData = $('#image_new_file').val();
        if (imageData.length != 0) {
            formData.append("file", $('#image_new_file')[0].files[0]);
            formData.append("operation", operation);
        }
    } else {//修改
        imageData = $('#image_edit_file').val();
        if (imageData.length != 0) {
            formData.append("fileId", fileId);
            formData.append("file", $('#image_edit_file')[0].files[0]);
        }

    }
    if (imageData.length != 0) {
        $.ajax({
            type: "post",
            url: ctp + "/sysFile/uploadImage",
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (result) {
                if (result.code == "200") {
                    var url = ctp + "/static/" + result.data.fileUrl;
                    fileId = result.data.fileId;
                    //上传成功之后清空输入框的值
                    if (operation == 'insert') {
                        $('#image_new_element').attr('src', url);
                    } else {
                        $('#image_edit_element').attr('src', url);
                    }
                } else {
                    alert(result.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    }
}

//保存上传元素方法
function uploadElementData(operation) {
    var formData = new FormData();
    formData.append('fileId', fileId);
    try {
        if (operation == 'insert') {//新增
            formData.append('groupId', groupId);
            formData.append('operation', 'insert');
            formData.append('configJson',JSON.stringify(jsoneditor_NewData.get()));
            formData.append('elementName', $('#element_name').val());
        } else {//编辑
            formData.append('elementId', elementId);
            formData.append('groupId', groupId);
            formData.append('elementName', $('#edit_element_name').val());
            formData.append('configJson',JSON.stringify(jsoneditor_data.get()));
        }
        $.ajax({
            type: "post",
            url: ctp + "/element/uploadElementData",
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            dataType: "json",
            success: function (result) {
                if (result.code == "200") {
                    queryElement(1);
                    alert(result.data);
                    $('#insertElementData').modal('close');
                    $("#editElementData").modal('close');

                    $('#image_new_element').attr('src', 'static/img/noPicture.png');
                    $('#image_edit_element').attr('src', '');

                    //清空输入框的内容
                    $('#element_name').val('');
                    $('#image_new_file').val('');
                    $('#config_json').val('');

                    $('#edit_element_name').val('');
                    $('#image_edit_file').val('');
                    $('#edit_config_json').val('');
                } else {
                    alert(result.msg);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("网络异常");
            }
        });
    }
    catch (err) {
        alert("输入的json格式不正确，请检查输入格式！！！");
    }

}

//查询通过 元素 名称
function queryByElementName(name) {
    var parm = {"elementName": name, "groupId": groupId, "current": 1, "size": 5};
    $.ajax({
        type: "post",
        url: ctp + "/element/query",
        cache: false,
        data: JSON.stringify(parm),
        dataType: "json",
        contentType: "application/json",
        success: function (result) {
            if (result.code == "200") {
                // 每次切换到下一页时清空当前div中的数据
                $("#multiplyElement").empty();
                // 循环添加图片表格
                listElementData(result.data.records);
                // 调用分页工具显示分页
                initPageElement('pageElement', result.data.current, result.data.size, result.data.total);
            } else {
                alert(result.msg);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络异常");
        }
    });
}

